<script setup lang="ts">
import { type TippyOptions, useTippy } from 'vue-tippy'

const props = withDefaults(defineProps<{
  type?: 'primary' | 'success' | 'warning' | 'danger' | 'info'
  size?: 'large' | 'default' | 'small'
  truncated?: boolean
  lineClamp?: number | string
  tag?: string
}>(), {
  truncated: false,
})
const textRef = ref()
const tippyFunc = ref()
const $slots = useSlots()

function isTextEllipsis(el: HTMLElement) {
  // 单行
  if (!props.lineClamp) {
    return el.scrollWidth > el.clientWidth
  }
  else {
    // 多行
    return el.scrollHeight > el.clientHeight
  }
}

function getTippyProps(): TippyOptions {
  return {
    content: h($slots.default as any),
    placement: 'right-start',
  }
}

function handleHover(event: MouseEvent) {
  if (isTextEllipsis(event.target as HTMLElement)) {
    tippyFunc.value.enable()
  }
  else {
    tippyFunc.value.disable()
  }
}

onMounted(() => {
  tippyFunc.value = useTippy(textRef.value?.$el, getTippyProps())
})
</script>

<template>
  <el-text
    ref="textRef"
    v-bind="props"
    @mouseover.self="handleHover"
  >
    <slot />
  </el-text>
</template>

<style scoped>
.sy-text {
  color: inherit;
}
</style>
